<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="110px"
      v-loading="formLoading"
    >
      <el-form-item label="问卷名称" prop="paperName">
        <el-input v-model.trim="formData.paperName" placeholder="请输入问卷名称" maxLength="50" />
      </el-form-item>
      <el-form-item label="问卷状态" prop="paperStatus">
        <el-select v-model="formData.paperStatus" placeholder="请选择问卷状态" clearable disabled>
          <el-option
            v-for="dict in paperStatusList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="单选题数量" prop="singleChoiceTotal">
        <el-input-number
          v-model.trim="formData.singleChoiceTotal"
          placeholder="请输入单选数量"
          :precision="0"
          :min="0"
          :max="99999999"
          :step="1"
          class="!w-full"
        />
      </el-form-item>
      <el-form-item label="多选题数量" prop="multipleChoiceTotal">
        <el-input-number
          v-model.trim="formData.multipleChoiceTotal"
          placeholder="请输入多选数量"
          :precision="0"
          :min="0"
          :max="99999999"
          :step="1"
          class="!w-full"
        />
      </el-form-item>
      <el-form-item label="判断题数量" prop="judgeTotal">
        <el-input-number
          v-model.trim="formData.judgeTotal"
          placeholder="请输入判断数量"
          :precision="0"
          :min="0"
          :max="99999999"
          :step="1"
          class="!w-full"
        />
      </el-form-item>
      <el-form-item label="简答题数量" prop="shortAnswerTotal">
        <el-input-number
          v-model.trim="formData.shortAnswerTotal"
          placeholder="请输入简答数量"
          :precision="0"
          :min="0"
          :max="99999999"
          :step="1"
          class="!w-full"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
const { t } = useI18n() // 国际化

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  paperName: undefined,
  paperStatus: 1,
  singleChoiceTotal: 0,
  multipleChoiceTotal: 0,
  judgeTotal: 0,
  shortAnswerTotal: 0
})

const formRules = reactive({
  paperName: [{ required: true, message: '问卷名称不能为空', trigger: 'blur' }],
  singleChoiceTotal: [{ required: true, message: '单选题数量不能为空', trigger: 'blur' }],
  multipleChoiceTotal: [{ required: true, message: '多选题数量不能为空', trigger: 'blur' }],
  judgeTotal: [{ required: true, message: '判断题数量不能为空', trigger: 'blur' }],
  shortAnswerTotal: [{ required: true, message: '简答题数量不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const list = ref([]) //全部数据

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  const saved = window.localStorage.getItem('paperList')
  list.value = saved ? JSON.parse(saved) : []
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = list.value.find((obj) => obj.id === id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) return
  if (formData.value.id) {
    list.value = replaceById(list.value, formData.value.id, formData.value)
  } else {
    formData.value.id = randomId10() //给一个id
    list.value.push(formData.value)
  }
  // 提交请求
  formLoading.value = true
  try {
    // 把题目存到store
    window.localStorage.setItem('paperList', JSON.stringify(list.value))
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    paperName: undefined,
    paperStatus: 1,
    singleChoiceTotal: 0,
    multipleChoiceTotal: 0,
    judgeTotal: 0,
    shortAnswerTotal: 0
  }
  list.value = []
  formRef.value?.resetFields()
}

// 问卷状态
const paperStatusList = reactive([
  { value: 1, label: '未发布' },
  { value: 2, label: '已发布' }
])

/**
 * 生成 10 位随机数字字符串（纯数字）
 * 例：4729385610
 */
function randomId10(): string {
  return String(Math.floor(Math.random() * 9_000_000_000) + 1_000_000_000)
}

/**
 * 按 id 精准替换数组中的某一项
 * 如果找到，就地替换并返回新数组；找不到原样返回
 */
function replaceById<T extends { id: string | number }>(
  list: T[],
  id: string | number,
  newData: Partial<T>
): T[] {
  return list.map((item) =>
    String(item.id) === String(id)
      ? { ...item, ...newData } // 合并老对象与新数据
      : item
  )
}
</script>
